from flask import Flask, render_template, request, redirect, jsonify, Blueprint,g
from datetime import date, timedelta
from forms import ShareFileForm
from models import User, File, SharedFile
import Encryption_and_decryption as ed

share = Blueprint("share", __name__)


# 用户对指定文件发起分享页面
@share.route("/<int:file_id>/share", methods=["GET", "POST"])
def share_(file_id):
    user = g.user
    if not user:
        redirect('/')
    form = ShareFileForm()
    file_ = File.query.get(file_id)
    form.file_name.data = file_.file_name
    # 验证文件数字签名完整性模块
    # 若文件完整性缺失则直接抛出异常
    # --- #
    if request.method == "GET":
        # 跳转分享发起页面
        return render_template("share.html", form=form)
    if request.method == "POST":
        if not form.validate():
            # 获取第一个错误信息
            error = next(iter(form.errors.values()))[0]
            return render_template("share.html", form=form, error=error)

        # 数据存入db.shared_file
        form = ShareFileForm(request.form)
        form.file_name.data = file_.file_name

        new_share = SharedFile(file_id=file_id)
        date_limit = date.today()

        if form.share_type.data == "code":
            # access_com 待加密 慢速哈希 密文形式存储
            user_ = User.query.get(file_.user_id)
            access_hash = ed.get_hash_from_str(form.code_input.data)
            new_share.access_com = access_hash
        if form.date_limit.data == "diy":
            date_limit = form.date_select.data
        elif form.date_limit.data != "forever":
            date_limit = date.today() + timedelta(
                days=int(form.date_limit.data)
            )
        if form.counts_limit.data == "diy":
            new_share.counts_flag = True
            new_share.counts_limit = form.counts_input.data
        else:
            new_share.counts_flag = False
        from database import db

        db.session.add(new_share)
        db.session.commit()
        # 返回生成的临时url
        # 分享序号share_id 分享文件编号file_id 有效期限date_limit
        # 均于 JWT编码 中表示
        import jwt

        jwt_json = {
            "share_id": str(new_share.share_id),
            "file_id": str(new_share.file_id),
            "date_limit": str(date_limit),
        }
        # 通过 用户密码 hash_password 盐值 user_salt
        # 派生公私钥对 再使用HMAC进行签名
        user_ = User.query.get(file_.user_id)
        jwt_tmp = {"hash_password": user_.hash_password, "user_salt": user_.user_salt}
        url = jwt.jwt_generate(jwt_json, jwt_tmp)
        return render_template("share.html", form=form, url=url)
